package edu.hda.pt.client.connections.netty;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;

import edu.hda.pt.client.connections.PTClientNetty;
import edu.hda.pt.utils.Stream.StreamState;

/**
 * Event handler for receiving asynchronous messages
 * 
 * @author Marc Hammerton
 * 
 */
@ChannelPipelineCoverage("one")
public class AsyncClientHandler extends ClientHandler {

	private PTClientNetty client;

	/**
	 * Constructor setting the client object
	 * 
	 * @param client
	 *            - client object
	 */
	public AsyncClientHandler(PTClientNetty client) {
		this.client = client;
	}

	/**
	 * This method is called when a message from the server is received. It
	 * notifies the client that a message is received.
	 * 
	 * @see org.jboss.netty.channel.SimpleChannelHandler#messageReceived(ChannelHandlerContext,
	 *      MessageEvent)
	 */
	@Override
	public void messageReceived(ChannelHandlerContext chx, final MessageEvent e) {

		if (client.stream.getState() == StreamState.START) {
			client.stream.setState(StreamState.RUNNING);
		}
		synchronized (client) {
			client.notify();
		}

	}

	/**
	 * This method is called whenever an exception is caught. It prints the
	 * exception.
	 * 
	 * @see org.jboss.netty.channel.SimpleChannelHandler#exceptionCaught(ChannelHandlerContext,
	 *      ExceptionEvent)
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		System.out.println(client.clientID + " Exception:");
		System.out.println(e.getCause());
	}

	/**
	 * @see edu.hda.pt.client.connections.netty.ClientHandler#responseReceived()
	 */
	@Override
	public String responseReceived() {
		return null;
	}

}
